<template>
  <div class="finance-applications-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>我的融资申请记录</h2>
    </div>

    <!-- 申请列表区域 -->
    <el-card class="applications-card">
      <!-- 加载状态 -->
      <el-skeleton
          v-if="loading"
          :rows="5"
          animated
          style="padding: 20px 0"
      />

      <!-- 列表展示（新增操作列：取消申请） -->
      <el-table
          v-else-if="applications.length > 0"
          :data="applications"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column
            prop="amount"
            label="申请金额(元)"
            width="130"
            align="center"
        >
          <template #default="scope">
            {{ scope.row.amount ? Number(scope.row.amount).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="purpose"
            label="申请用途"
            min-width="150"
        />
        <el-table-column
            prop="term"
            label="期限(月)"
            width="100"
            align="center"
        />
        <el-table-column
            prop="interestRate"
            label="年利率(%)"
            width="120"
            align="center"
        >
          <template #default="scope">
            {{ scope.row.interestRate ? Number(scope.row.interestRate).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="applyTime"
            label="申请时间"
            width="180"
            align="center"
        >
          <template #default="scope">
            {{ formatDate(scope.row.applyTime) || '-' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="申请状态"
            width="120"
            align="center"
        >
          <template #default="scope">
            <el-tag
                :type="getStatusType(scope.row.status)"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 新增：操作列（取消申请按钮） -->
        <el-table-column
            label="操作"
            width="120"
            align="center"
        >
          <template #default="scope">
            <!-- 仅「待审核」(status=0) 状态显示可点击的取消按钮，其他状态禁用 -->
            <el-button
                size="small"
                type="danger"
                @click="handleCancel(scope.row)"
                :disabled="scope.row.status !== 0"
                :loading="cancelLoading[scope.row.financeId]"
            >
              取消申请
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty
            description="暂无融资申请记录"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

// 导入接口：新增取消申请接口（需后端配合实现对应接口）
import {
  getFinanceApplicationsByUserId,
  cancelFinanceApplication  // 新增：取消申请接口（后续需与后端接口对齐）
} from '@/apis/financeApplicationApi.js'

// 用户状态
const userStore = useUserStore()

// 数据状态
const loading = ref(true)
const applications = ref([])
// 新增：取消按钮加载状态（按financeId存储，避免多条申请加载状态冲突）
const cancelLoading = ref<Record<number, boolean>>({})

// 页面加载时获取列表
onMounted(() => {
  if (!userStore.isLogin || !userStore.userInfo.uid) {
    ElMessage.warning('请先登录后查看融资申请')
    return
  }
  fetchUserApplications()
})

// 获取用户申请列表（不变）
const fetchUserApplications = async () => {
  try {
    loading.value = true
    const currentUserId = userStore.userInfo.uid
    const res = await getFinanceApplicationsByUserId(currentUserId)

    if (res?.success) {
      applications.value = res.data || []
    } else {
      ElMessage.error(`获取申请失败：${res?.message || '未知错误'}`)
      applications.value = []
    }
  } catch (error) {
    console.error('获取融资申请列表异常：', error)
    ElMessage.error('网络异常，请检查连接后重试')
    applications.value = []
  } finally {
    loading.value = false
  }
}

// 新增：处理取消申请逻辑
const handleCancel = async (application: any) => {
  // 用ElMessageBox.confirm替代ElConfirm
  ElMessageBox.confirm(
      `您确定要取消申请ID【${application.financeId}】的融资申请吗？取消后不可恢复。`,
      '确认取消申请？',
      {
        type: 'warning',
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
      }
  )
      .then(async () => {
        // 点击"确认取消"的逻辑
        cancelLoading.value[application.financeId] = true
        try {
          const res = await cancelFinanceApplication({
            financeId: application.financeId,
            cancelReason: '用户主动取消融资申请'
          })
          if (res?.success) {
            ElMessage.success('取消申请成功！')
            await fetchUserApplications()
          } else {
            ElMessage.error(`取消失败：${res?.message || '未知错误'}`)
          }
        } catch (error) {
          console.error('取消申请异常：', error)
          ElMessage.error('网络异常，取消申请失败')
        } finally {
          cancelLoading.value[application.financeId] = false
        }
      })
      .catch(() => {
        // 点击"取消"或关闭弹窗，不做任何操作
      })
}

// 格式化日期（不变）
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 状态文本转换（新增"已取消"状态，需后端同步返回status=6）
const getStatusText = (status: number | undefined) => {
  const statusMap = {
    0: '待审核',
    1: '审核通过',
    2: '审核拒绝',
    3: '已放款',
    4: '已还款',
    5: '逾期',
    6: '已取消'  // 新增：已取消状态
  }
  return statusMap[status as number] || '未知状态'
}

// 状态标签样式（新增"已取消"样式：灰色）
const getStatusType = (status: number | undefined) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'primary',
    4: 'warning',
    5: 'danger',
    6: 'default'  // 新增：已取消-灰色标签
  }
  return typeMap[status as number] || 'default'
}
</script>

<style scoped lang="less">
.finance-applications-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #1f2937;
    font-size: 18px;
    font-weight: 600;
  }
}

.applications-card {
  width: 100%;
  height: auto;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .empty-state {
    padding: 60px 0;
    text-align: center;
  }
}

// 可选：优化禁用状态按钮的样式（更明显）
:deep(.el-button--danger.is-disabled) {
  color: #999 !important;
  background-color: #fef2f2 !important;
  border-color: #fcd5d5 !important;
  cursor: not-allowed;
}
</style>